package org.linlinjava.litemall.wx.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.PiccMessagePackage;
import org.linlinjava.litemall.db.domain.PiccPatient;
import org.linlinjava.litemall.db.service.PiccMessagePackageService;
import org.linlinjava.litemall.db.service.PiccNurseService;
import org.linlinjava.litemall.db.service.PiccPatientService;
import org.linlinjava.litemall.wx.dto.PiccMessageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class WxPiccMessageService {
    private final Log logger = LogFactory.getLog(WxPiccMessageService.class);
    @Autowired
    PiccMessagePackageService piccMessagePackageService;

    @Autowired
    PiccPatientService piccPatientService;

    @Autowired
    PiccNurseService piccNurseService;

    /**
     * 添加聊天记录
     * @param msg
     * @return
     */
    public PiccMessagePackage add(PiccMessagePackage msg){
        piccMessagePackageService.add(msg);
        return msg;
    }
    /**
     * 列出护士名下的所有聊天记录的预览情况，包括病人头像，未读消息，最新一条信息
     * @param nurseId
     * @return
     */
    public Object listByNurse(int nurseId, int patientId, String role){
        if (role.equals("n")){
            //护士查询预览详情
            List<PiccMessageInfo> infoList = new ArrayList<PiccMessageInfo>();
            //1、查到这个护士名下的所有病人列表；
            List<PiccPatient> patientList = piccPatientService.getPatientsByNurseId(nurseId, 0, 0, "id", "desc");

            //2. 开始遍历，并组装
            for (int i = 0; i < patientList.size(); i++) {
                //病人id和病人name
                int pId = patientList.get(i).getId();
                String pName = patientList.get(i).getName();

                //先查询未读消息
                List<PiccMessagePackage> unreadMsgList = piccMessagePackageService.getMessagesByStatus(pId, nurseId, role, "add_time", "desc", false);
                List<PiccMessagePackage> readMsgList = piccMessagePackageService.getMessagesByIds(pId, nurseId, "add_time", "desc");
                List<PiccMessagePackage> messagePackageList;
                int mSize = 0;
                if (unreadMsgList.size() != 0) {
					//如果有未读消息，则unread为未读消息的数量；
                    messagePackageList = unreadMsgList;
                    mSize = unreadMsgList.size();
                }
                else
					//否则，msize还是0
                    messagePackageList = readMsgList;
				//如果未读和已读消息都是0，则和这个病人没有聊天记录，直接跳出循环
                if (messagePackageList.size() == 0)
                    continue;

                //最后一条msg
                String latestMsg = null;
                //如果最新一条是文字，则作为预览信息返回给小程序
                if (messagePackageList.get(0).getType().equals("text")) {
                    latestMsg = messagePackageList.get(0).getContent();
                }else if (messagePackageList.get(0).getType().equals("image")) {
                    latestMsg = "[图片]";
                }

                //最后一条的时间
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String latestTime = dateTimeFormatter.format(messagePackageList.get(0).getAddTime());

                PiccMessageInfo info = new PiccMessageInfo(mSize, pId, nurseId, null, latestMsg, pName, latestTime);
                infoList.add(info);
            }
            logger.debug(infoList);

            return ResponseUtil.ok(infoList);
        }else if(role.equals("p")){
            //病人获取预览详情
            List<PiccMessagePackage> messagePackageList = piccMessagePackageService.getMessagesByStatus(patientId, nurseId, role,"add_time", "desc", false);
            int mSize = messagePackageList.size();
            PiccMessageInfo info = new PiccMessageInfo(mSize, patientId, nurseId, null, null, null, null);
            return ResponseUtil.ok(info);
        }else
            return ResponseUtil.fail();

    }

    /**
     * 获取聊天详情，根据病人id，护士id，和role来进行数据库的转换
     * @param patientId
     * @param nurseId
     * @param role p是病人，n是护士
     * @param sort
     * @param order
     * @return
     */
    public Object contentByIds(int patientId, int nurseId, String role, String sort, String order){
        logger.debug(patientId+", "+nurseId+", "+role);
        List<PiccMessagePackage> mList = piccMessagePackageService.getMessagesByIds(patientId, nurseId, sort, order);
        logger.debug("getMsgContent: "+mList);
        List<PiccMessagePackage> mListCopy;

        try {
            mListCopy = deepCopy(mList);
        }catch (Exception e){
            logger.debug(e);
            return ResponseUtil.okList(mList);
        }

        PiccMessagePackage msgPackage;
        for (int i=0; i<mList.size(); i++){
            msgPackage = mList.get(i);
            //一旦前端get了之后
            //如果这次查询详情的角色，不是发送者，那么就将消息设为已读，否则就不设置
            if (!role.equals(msgPackage.getSender()) && !msgPackage.getStatus()) {
                msgPackage.setStatus(true);
                piccMessagePackageService.updateById(msgPackage);
            }
        }
        logger.debug("getMsgContent copy:"+mListCopy);
        return ResponseUtil.okList(mListCopy);
    }

    private <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);

        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        @SuppressWarnings("unchecked")
        List<T> dest = (List<T>) in.readObject();
        return dest;
    }
}
